package com.csu.tingtian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.tingtian.common.CommonResponse;
import com.csu.tingtian.entity.LegalFarm;
import com.csu.tingtian.entity.ProvideProduce;
import com.csu.tingtian.entity.RentFarm;
import com.csu.tingtian.persistence.LegalFarmMapper;
import com.csu.tingtian.persistence.RentFarmMapper;
import com.csu.tingtian.service.FarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("farmService")
public class FarmServiceImpl implements FarmService {
    @Autowired
    private RentFarmMapper rentFarmMapper;
    @Autowired
    private LegalFarmMapper legalFarmMapper;


    //商家上架农场，改变legalfarm中的状态为1
    @Override
    public CommonResponse<String> changeStatus(String farmName) {
        QueryWrapper<LegalFarm> queryWrapper = new QueryWrapper<>();
        //先找到这个farm
        LegalFarm legalFarm = legalFarmMapper.selectById(farmName);

        //改变isRent为1
        legalFarm.setIsRent(1);

        //更新
        legalFarmMapper.updateById(legalFarm);
        return CommonResponse.createForSuccess("上架成功");
    }

    //商家上架农场，选择可种植的农产品
    @Override
    public CommonResponse<RentFarm> insertRentFarm(String id, String farmName) {
        RentFarm rentFarm = new RentFarm();
        //判断是蔬菜还是水果
        if(id.startsWith("V"))
            rentFarm.setVegetableId(id);
        if(id.startsWith("F"))
            rentFarm.setFruitId(id);

        rentFarm.setFarmName(farmName);

        rentFarmMapper.insert(rentFarm);

        return CommonResponse.createForSuccess("插入成功",rentFarm);
    }

    //获取所有出租农场的信息
    @Override
    public CommonResponse<List<LegalFarm>> getAllRentFarm() {
        QueryWrapper<LegalFarm> queryWrapper = new QueryWrapper<>();
        //isRent字段为1，即该农场已上架
        List<LegalFarm> list = legalFarmMapper.selectList(queryWrapper.eq("isRent",1));
        return CommonResponse.createForSuccess(list);
    }


    //用户租赁农场后，更新该农场的farmFreeArea，即更新legalFarm表
    @Override
    public CommonResponse<String> updateArea(String farmName,int area) {
        LegalFarm legalFarm = legalFarmMapper.selectById(farmName);

        legalFarm.setFarmFreeArea(area);

        legalFarmMapper.updateById(legalFarm);

        return CommonResponse.createForSuccess("更新成功");
    }
}
